<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.json',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="优雅的等待goroutine退出通过Channel传递退出信号Go的一大设计哲学就是：通过Channel共享数据，而不是通过共享内存共享数据。主流程可以通过channel向任何goroutine发送停止信号，就像下面这样： 这种方式可以实现优雅地停止goroutine，但是当goroutine特别多的时候，这种方式不管在代码美观上还是管理上都显得笨拙不堪。 12345678910111213141">
<meta name="keywords" content="golang">
<meta property="og:type" content="article">
<meta property="og:title" content="golang优雅的等待或通知goroutine退出">
<meta property="og:url" content="https://unix2dos.github.io/p/aca47db0.html">
<meta property="og:site_name" content="Levon&#39;s Blog">
<meta property="og:description" content="优雅的等待goroutine退出通过Channel传递退出信号Go的一大设计哲学就是：通过Channel共享数据，而不是通过共享内存共享数据。主流程可以通过channel向任何goroutine发送停止信号，就像下面这样： 这种方式可以实现优雅地停止goroutine，但是当goroutine特别多的时候，这种方式不管在代码美观上还是管理上都显得笨拙不堪。 12345678910111213141">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-09-27T15:36:51.099Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="golang优雅的等待或通知goroutine退出">
<meta name="twitter:description" content="优雅的等待goroutine退出通过Channel传递退出信号Go的一大设计哲学就是：通过Channel共享数据，而不是通过共享内存共享数据。主流程可以通过channel向任何goroutine发送停止信号，就像下面这样： 这种方式可以实现优雅地停止goroutine，但是当goroutine特别多的时候，这种方式不管在代码美观上还是管理上都显得笨拙不堪。 12345678910111213141">
  <link rel="canonical" href="https://unix2dos.github.io/p/aca47db0">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>golang优雅的等待或通知goroutine退出 | Levon's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Levon's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">微信:  L6241425</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>时光</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://unix2dos.github.io/p/aca47db0.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Levon">
      <meta itemprop="description" content="Never Give Up">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Levon's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">golang优雅的等待或通知goroutine退出

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2018-05-28 00:03:21" itemprop="dateCreated datePublished" datetime="2018-05-28T00:03:21+08:00">2018-05-28</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-27 23:36:51" itemprop="dateModified" datetime="2019-09-27T23:36:51+08:00">2019-09-27</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/" itemprop="url" rel="index"><span itemprop="name">1-编程语言</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/1-编程语言/golang/" itemprop="url" rel="index"><span itemprop="name">golang</span></a></span>

                
                
              
            </span>
          

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Disqus：</span>
    
    <a title="disqus" href="/p/aca47db0.html#comments" itemprop="discussionUrl"><span class="post-comments-count disqus-comment-count" data-disqus-identifier="p/aca47db0.html" itemprop="commentCount"></span></a>
  </span>
  
  
          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              
                <span class="post-meta-item-text">本文字数：</span>
              
              <span>5.2k</span>
            </span>
          
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              
              <span>5 分钟</span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="优雅的等待goroutine退出"><a href="#优雅的等待goroutine退出" class="headerlink" title="优雅的等待goroutine退出"></a>优雅的等待goroutine退出</h3><h4 id="通过Channel传递退出信号"><a href="#通过Channel传递退出信号" class="headerlink" title="通过Channel传递退出信号"></a>通过Channel传递退出信号</h4><p>Go的一大设计哲学就是：通过Channel共享数据，而不是通过共享内存共享数据。主流程可以通过channel向任何goroutine发送停止信号，就像下面这样：</p>
<p>这种方式可以实现优雅地停止goroutine，但是当goroutine特别多的时候，这种方式不管在代码美观上还是管理上都显得笨拙不堪。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">   &quot;fmt&quot;</span><br><span class="line">   &quot;time&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">func run(done chan int) &#123;</span><br><span class="line">   for &#123;</span><br><span class="line">      select &#123;</span><br><span class="line">      case &lt;-done:</span><br><span class="line">         fmt.Println(&quot;exiting...&quot;)</span><br><span class="line">         done &lt;- 1</span><br><span class="line">         break</span><br><span class="line">      default:</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      time.Sleep(time.Second * 1)</span><br><span class="line">      fmt.Println(&quot;do something&quot;)</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line">   c := make(chan int)</span><br><span class="line"></span><br><span class="line">   go run(c)</span><br><span class="line"></span><br><span class="line">   fmt.Println(&quot;wait&quot;)</span><br><span class="line">   time.Sleep(time.Second * 5)</span><br><span class="line"></span><br><span class="line">   c &lt;- 1</span><br><span class="line">   &lt;-c</span><br><span class="line"></span><br><span class="line">   fmt.Println(&quot;main exited&quot;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<a id="more"></a>

<h4 id="使用Waitgroup"><a href="#使用Waitgroup" class="headerlink" title="使用Waitgroup"></a>使用Waitgroup</h4><p>通常情况下，我们像下面这样使用waitgroup:</p>
<ol>
<li>创建一个Waitgroup的实例，假设此处我们叫它wg</li>
<li>在每个goroutine启动的时候，调用wg.Add(1)，这个操作可以在goroutine启动之前调用，也可以在goroutine里面调用。当然，也可以在创建n个goroutine前调用wg.Add(n)</li>
<li>当每个goroutine完成任务后，调用wg.Done()</li>
<li>在等待所有goroutine的地方调用wg.Wait()，它在所有执行了wg.Add(1)的goroutine都调用完wg.Done()前阻塞，当所有goroutine都调用完wg.Done()之后它会返回。</li>
</ol>
<p>那么，如果我们的goroutine是一匹不知疲倦的牛，一直孜孜不倦地工作的话，如何在主流程中告知并等待它退出呢？像下面这样做：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line">package main</span><br><span class="line"></span><br><span class="line">import (</span><br><span class="line">   &quot;fmt&quot;</span><br><span class="line">   &quot;os&quot;</span><br><span class="line">   &quot;os/signal&quot;</span><br><span class="line">   &quot;sync&quot;</span><br><span class="line">   &quot;syscall&quot;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line">type Service struct &#123;</span><br><span class="line">   // Other things</span><br><span class="line"></span><br><span class="line">   ch        chan bool</span><br><span class="line">   waitGroup *sync.WaitGroup</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func NewService() *Service &#123;</span><br><span class="line">   s := &amp;Service&#123;</span><br><span class="line">      // Init Other things</span><br><span class="line">      ch:        make(chan bool),</span><br><span class="line">      waitGroup: &amp;sync.WaitGroup&#123;&#125;,</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   return s</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func (s *Service) Stop() &#123;</span><br><span class="line">   close(s.ch)</span><br><span class="line">   s.waitGroup.Wait()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func (s *Service) Serve() &#123;</span><br><span class="line">   s.waitGroup.Add(1)</span><br><span class="line">   defer s.waitGroup.Done()</span><br><span class="line"></span><br><span class="line">   for &#123;</span><br><span class="line">      select &#123;</span><br><span class="line">      case &lt;-s.ch:</span><br><span class="line">         fmt.Println(&quot;stopping...&quot;)</span><br><span class="line">         return</span><br><span class="line">      default:</span><br><span class="line">      &#125;</span><br><span class="line">      s.waitGroup.Add(1)</span><br><span class="line">      go s.anotherServer()</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line">func (s *Service) anotherServer() &#123;</span><br><span class="line">   defer s.waitGroup.Done()</span><br><span class="line">   for &#123;</span><br><span class="line">      select &#123;</span><br><span class="line">      case &lt;-s.ch:</span><br><span class="line">         fmt.Println(&quot;stopping...&quot;)</span><br><span class="line">         return</span><br><span class="line">      default:</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      // Do something</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">func main() &#123;</span><br><span class="line"></span><br><span class="line">   service := NewService()</span><br><span class="line">   go service.Serve()</span><br><span class="line"></span><br><span class="line">   // Handle SIGINT and SIGTERM.</span><br><span class="line">   ch := make(chan os.Signal)</span><br><span class="line">   signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)</span><br><span class="line">   fmt.Println(&lt;-ch)</span><br><span class="line"></span><br><span class="line">   // Stop the service gracefully.</span><br><span class="line">   service.Stop()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="优雅的通知-goroutine-退出"><a href="#优雅的通知-goroutine-退出" class="headerlink" title="优雅的通知 goroutine 退出"></a>优雅的通知 goroutine 退出</h3><p>有时候我们需要通知goroutine停止它正在干的事情，比如一个正在执行计算的web服务，然而它的客户端已经断开了和服务端的连接。</p>
<p>Go语言并没有提供在一个goroutine中终止另一个goroutine的方法，由于这样会导致goroutine之间的共享变量落在未定义的状态上。</p>
<p>在rocket launch程序中，我们往名字叫abort的channel里发送了一个简单的值，在countdown的goroutine中会把这个值理解为自己的退出信号。但是如果我们想要退出两个或者任意多个goroutine怎么办呢？</p>
<p>一种可能的手段是向abort的channel里发送和goroutine数目一样多的事件来退出它们。如果这些goroutine中已经有一些自己退出了，那么会导致我们的channel里的事件数比goroutine还多，这样导致我们的发送直接被阻塞。另一方面，如果这些goroutine又生成了其它的goroutine，我们的channel里的数目又太少了，所以有些goroutine可能会无法接收到退出消息。一般情况下我们是很难知道在某一个时刻具体有多少个goroutine在运行着的。</p>
<p>另外，当一个goroutine从abort channel中接收到一个值的时候，他会消费掉这个值，这样其它的goroutine就没法看到这条信息。为了能够达到我们退出goroutine的目的，我们需要更靠谱的策略，来通过一个channel把消息广播出去，这样goroutine们能够看到这条事件消息，并且在事件完成之后，可以知道这件事已经发生过了。</p>
<p>回忆一下我们关闭了一个channel并且被消费掉了所有已发送的值，操作channel之后的代码可以立即被执行，并且会产生零值。我们可以将这个机制扩展一下，来作为我们的广播机制：<strong><em>不要向channel发送值，而是用关闭一个channel来进行广播。</em></strong></p>
<h3 id="优雅的控制-goroutine-退出"><a href="#优雅的控制-goroutine-退出" class="headerlink" title="优雅的控制 goroutine 退出"></a>优雅的控制 goroutine 退出</h3><p>通常<code>Goroutine</code>会因为两种情况阻塞：</p>
<ol>
<li>IO操作，比如对<code>Socket</code>的<code>Read</code>。</li>
<li><code>channel</code>操作。对一个chan的读写都有可能阻塞<code>Goroutine</code>。</li>
</ol>
<p>对于情况1，只需要关闭对应的描述符，阻塞的<code>Goroutine</code>自然会被唤醒。</p>
<p>重点讨论情况2。并发编程，<code>Goroutine</code>提供一种<code>channel</code>机制，<code>channel</code>类似管道，写入者向里面写入数据，读取者从中读取数据。如果<code>channel</code>里面没有数据，读取者将阻塞，直到有数据；如果<code>channel</code>里面数据满了，写入者将因为无法继续写入数据而阻塞。</p>
<p>如果在整个应用程序的生命周期里，writer和reader都表现为一个<code>Goroutine</code>，始终都在工作，那么如何在应用程序结束前，通知它们终止呢？在Go中，并不推荐像abort线程那样，强行的终止<code>Goroutine</code>。因此，抽象的说，必然需要保留一个入口，能够跟writer或reader通信，以告知它们终止。</p>
<p>我们先看reader。我们首先可以想到，利用<code>close</code>函数关闭正在读取的<code>channel</code>，从而可以唤醒reader，并退出。但是考虑到<code>close</code>并不能很好的处理writer（因为writer试图写入一个已经close的channel，将引发异常）。因此，我们需要设计一个额外的只读<code>channel</code>用于通知：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">type routineSignal struct &#123;</span><br><span class="line">    done &lt;-chan struct&#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> <code>routineSignal</code>的实例，应当通过外部生成并传递给reader，例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">func (r *reader)init(s *routineSignal) &#123;</span><br><span class="line">    r.signal = s</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 在reader的循环中，就可以这么写：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">func (r *reader)loop() &#123;</span><br><span class="line">    for &#123;</span><br><span class="line">        select &#123;</span><br><span class="line">        case &lt;-r.signal.done:</span><br><span class="line">            return</span><br><span class="line">        case &lt;-r.queue:</span><br><span class="line">            ....</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当需要终止<code>Goroutine</code>的时候只需要关闭这个额外的<code>channel</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">close(signal.done)</span><br></pre></td></tr></table></figure>





<p>看起来很完备了，这可以处理大部分的情况了。这样做有个弊端，尽管，我们可以期望<code>close</code>唤醒<code>Goroutine</code>进而退出，但是并不能知道<code>Goroutine</code>什么时候完成退出，因为<code>Goroutine</code>可能在退出前还有一些善后工作，这个时候我们需要<code>sync.WaitGroup</code>。改造一下<code>routineSignal</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">type routineSignal struct &#123;</span><br><span class="line">    done chan struct&#123;&#125;</span><br><span class="line">    wg   sync.WaitGroup</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>增加一个sync.WaitGroup的实例，在<code>Goroutine</code>开始工作时，对wg加1，在<code>Goroutine</code>退出前，对wg减1：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">func (r *reader)loop() &#123;</span><br><span class="line">    r.signal.wg.Add(1)</span><br><span class="line">    defer r.signal.wg.Done()</span><br><span class="line">    for &#123;</span><br><span class="line">        select &#123;</span><br><span class="line">        case &lt;-r.signal.done:</span><br><span class="line">            return</span><br><span class="line">        case &lt;-r.queue:</span><br><span class="line">            ....</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p> 外部，只需要等待<code>WaitGroup</code>返回即可：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">close(signal.done)</span><br><span class="line">signal.wg.Wait()</span><br></pre></td></tr></table></figure>

<p>只要<code>Wait()</code>返回就能断定<code>Goroutine</code>结束了。</p>
<p>推导一下，不难发现，对于writer也可以采用这种方法。于是，总结一下，我们创建了一个叫<code>routineSignal</code>的结构，结构里面包含一个<code>chan</code>用来通知<code>Goroutine</code>结束，包含一个<code>WaitGroup</code>用于<code>Goroutine</code>通知外部完成善后。这样，通过这个结构的实例优雅的终止<code>Goroutine</code>，而且还可以确保<code>Goroutine</code>终止成功。 </p>

    </div>

    
    
    
        
      
        <div id="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作, 一个耿直的笑脸~</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Levon 微信支付">
        <p>微信支付</p>
      </div>
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="Levon 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/golang/" rel="tag"># golang</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/p/8b210700.html" rel="next" title="golang优雅的关闭channel">
                  <i class="fa fa-chevron-left"></i> golang优雅的关闭channel
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/p/d43abcbd.html" rel="prev" title="linux开启ftp服务和golang实现ftp_server_client">
                  linux开启ftp服务和golang实现ftp_server_client <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    
  <div class="comments" id="comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
    </div>
  </div>
  
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#优雅的等待goroutine退出"><span class="nav-number">1.</span> <span class="nav-text">优雅的等待goroutine退出</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#通过Channel传递退出信号"><span class="nav-number">1.1.</span> <span class="nav-text">通过Channel传递退出信号</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用Waitgroup"><span class="nav-number">1.2.</span> <span class="nav-text">使用Waitgroup</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优雅的通知-goroutine-退出"><span class="nav-number">2.</span> <span class="nav-text">优雅的通知 goroutine 退出</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优雅的控制-goroutine-退出"><span class="nav-number">3.</span> <span class="nav-text">优雅的控制 goroutine 退出</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Levon">
  <p class="site-author-name" itemprop="name">Levon</p>
  <div class="site-description" itemprop="description">Never Give Up</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">76</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/unix2dos" title="GitHub &rarr; https://github.com/unix2dos" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:levonfly@gmail.com" title="E-Mail &rarr; mailto:levonfly@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://twitter.com/levonfly" title="Twitter &rarr; https://twitter.com/levonfly" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://weibo.com/l6241425" title="Weibo &rarr; https://weibo.com/l6241425" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Levon</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">507k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:41</span>
</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  <script src="/js/local-search.js?v=7.4.0"></script>














  

  

  

<script>
  function loadCount() {
    var d = document, s = d.createElement('script');
    s.src = 'https://levonfly.disqus.com/count.js';
    s.id = 'dsq-count-scr';
    (d.head || d.body).appendChild(s);
  }
  // defer loading until the whole page loading is completed
  window.addEventListener('load', loadCount, false);
</script>
<script>
  function disqus_config() {
    this.page.url = "https://unix2dos.github.io/p/aca47db0.html";
    this.page.identifier = "p/aca47db0.html";
    this.page.title = 'golang优雅的等待或通知goroutine退出';};
  function loadComments() {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://levonfly.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  }
    window.addEventListener('load', loadComments, false);
  
</script>

</body>
</html>
